package com.xiaomo.gitee.datamanager.security.handler;

import com.xiaomo.gitee.datamanager.aspect.log.anno.SysLog;
import com.xiaomo.gitee.datamanager.common.result.Result;
import com.xiaomo.gitee.datamanager.entity.User;
import com.xiaomo.gitee.datamanager.util.HttpUtils;
import com.xiaomo.gitee.datamanager.util.JwtUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@NoArgsConstructor
@Component
@Lazy(false)
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private JwtUtils jwtUtils;

    @Autowired
    public LoginSuccessHandler(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    @SysLog("用户通过页面登入")
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        /*String jwt = jwtUtils.generateJwt(((User) authentication.getPrincipal()).getId().toString());
        response.setHeader(JwtUtils.HTTP_HEADER,jwt);*/
        Cookie cookie = jwtUtils.getJwtCookie(((User) authentication.getPrincipal()).getId().toString());
        response.addCookie(cookie);
        response.sendRedirect("/doc.html");
        //HttpUtils.writeJson(response, Result.ok("登录成功",jwtUtils.generateJwt(((User) authentication.getPrincipal()).getId().toString())));
    }

}
